﻿using LatteCoffee.coffeemodel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LatteCoffee.coffeemake
{
    public class EWMMsg
    {
        private static EWMMsg instance;
        private EWMMsg() { }
        public static EWMMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new EWMMsg();
                }
                return instance;
            }
        }
        #region 二维码通讯
        public bool AllBol = true;
        public static Thread DecodeThread = null;
        delegate void ShowRichTextBoxMsgRef(System.Windows.Forms.RichTextBox lpRichTextBox, string lpMsg);
        //循环是否启动标记
        public static bool bIsLoop = false;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        string nostrs = "";
        public Thread All_thr;
        Vbarapi Api = new Vbarapi();
        public void IOSerial_Thr()
        {
            try
            {
                if (Api.openDevice())
                {
                    StartDecodeThread();
                }
                else
                {
                    Thread.Sleep(100);
                    IOSerial_Thr();
                }
            }
            catch (Exception)
            {
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        /// <summary>
        /// 方法：开始解码线程方法
        /// </summary>
        private void StartDecodeThread()
        {
            bIsLoop = true;
            DecodeThread = new Thread(new ThreadStart(DecodeThreadMethod));
            DecodeThread.IsBackground = true;
            DecodeThread.Start();
        }

        /// <summary>
        /// 方法：停止解码线程方法
        /// </summary>
        private void StopDecodeThread()
        {
            bIsLoop = false;
            if (DecodeThread != null)
            {
                DecodeThread.Abort();
                while (DecodeThread.ThreadState != ThreadState.Aborted)
                {
                    Thread.Sleep(50);
                }
            }
        }
        public string Decoder()
        {
            byte[] result;
            string sResult = null;
            int size;
            if (Api.getResultStr(out result, out size))
            {

                string msg = System.Text.Encoding.Default.GetString(result);
                byte[] buffer = Encoding.UTF8.GetBytes(msg);
                sResult = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            }
            else
            {
                sResult = null;
            }
            return sResult;
        }

        /// <summary>
        /// 方法：扫码线程方法
        /// </summary>
        private void DecodeThreadMethod()
        {
            string decoderesult = null;
            ShowRichTextBoxMsgRef ShowRichTextBoxMsgRef_Instance = new ShowRichTextBoxMsgRef(ShowRichTextBoxMsg);
            do
            {
                //+ Environment.NewLine
                decoderesult = Decoder();
                if (decoderesult != null)
                {
                    MsgShow(decoderesult);
                    decoderesult = null;
                }
            }
            while (bIsLoop);
        }
        /// <summary>
        /// 方法：显示文本信息
        /// </summary>
        /// <param name="lpRichTextBox"></param>
        /// <param name="lpMsg"></param>
        private void ShowRichTextBoxMsg(System.Windows.Forms.RichTextBox lpRichTextBox, string lpMsg)
        {
            lpRichTextBox.AppendText(lpMsg);
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                byte[] result = new byte[EWMSerialPort.Instance.serialPort.BytesToRead];
                EWMSerialPort.Instance.serialPort.Read(result, 0, EWMSerialPort.Instance.serialPort.BytesToRead);
                buffer.AddRange(result);
                string str = "";
                if (buffer.Count > 0x03)
                    str += $"{Encoding.ASCII.GetString(result)}";
                MsgShow(str);
                Thread.Sleep(1);
            }
            catch (Exception)
            {
                return;
            }
        }
        public void MsgShow(string str)
        {
            try
            {
                bool bol = true;
                switch (str)
                {
                    case "55 AA 29 01 00 00 D7":
                    case "55 AA 29 01 00 01 D6":
                    case "55 AA 29 01 00 02 D5":
                    case "55 AA 29 01 00 03 D4":
                        bol = false;
                        break;
                }
                if (bol)
                {
                    if (str.Length > 0)
                    {
                        var msgs = str.Split('*');
                        if (msgs.Count() >= 4)
                        {
                            if (nostrs.Length < 18)
                            {
                                str = nostrs + msgs[0];
                                nostrs = "";
                            }
                            else
                                str = msgs[0];
                            var msg = str.Split('#');
                            //if (Form1.isMake)
                            //{
                            if (msg.Count() > 1)
                            {
                                EWM eWM = new EWM();
                                eWM.orderNum = msg[0];
                                eWM.deviceId = msg[1];
                                string list = JsonConvert.SerializeObject(eWM);
                                Console.WriteLine(DateTime.Now.ToString() + " ewm");
                                var data = HttpMsg.Instance.orderQueueMsg(list);
                                Console.WriteLine(DateTime.Now.ToString() + " ewm");
                                if (data != null)
                                {
                                    var listdata = JsonConvert.DeserializeObject<HTTPMsg>(data);
                                    if (listdata != null)
                                    {
                                        switch (listdata.code)
                                        {
                                            case "0":
                                                var data1 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.SMCG);
                                                Api.Channel_show(data1);
                                                break;
                                            case "1":
                                                var data2 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.ZZZ);
                                                Api.Channel_show(data2);
                                                break;
                                            case "2":
                                                var data3 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.SMSB);
                                                Api.Channel_show(data3);
                                                break;
                                            case "3":
                                                var data4 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.CMYSY);
                                                Api.Channel_show(data4);
                                                break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                EWM eWM = new EWM();
                                eWM.orderNum = msg[0];
                                eWM.deviceId = "3";
                                eWM.type = 1;
                                string list = JsonConvert.SerializeObject(eWM);
                                Console.WriteLine(DateTime.Now.ToString() + " ewm");
                                var data = HttpMsg.Instance.orderQueueMsg(list);
                                Console.WriteLine(DateTime.Now.ToString() + " ewm");
                                if (data != null)
                                {
                                    var listdata = JsonConvert.DeserializeObject<HTTPMsg>(data);
                                    if (listdata != null)
                                    {
                                        switch (listdata.code)
                                        {
                                            case "0":
                                                var data1 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.SMCG);
                                                Api.Channel_show(data1);
                                                break;
                                            case "1":
                                                var data2 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.ZZZ);
                                                Api.Channel_show(data2);
                                                break;
                                            case "2":
                                                var data3 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.SMSB);
                                                Api.Channel_show(data3);
                                                break;
                                            case "3":
                                                var data4 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.CMYSY);
                                                Api.Channel_show(data4);
                                                break;
                                        }
                                    }
                                }
                                //  SpeechVoice.Instance.VoicePlayback(listdata.msg);
                            }
                            //}
                            //else
                            //{
                            //    var data = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.ZZZ);
                            //    Api.Channel_show(data);
                            //}
                        }
                        else if (msgs.Count() == 1)
                        {
                            nostrs = msgs[0];
                        }
                    }
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        public class EWM
        {
            public string orderNum { get; set; }
            public string deviceId { get; set; } = "3";
            public int type { get; set; } = 0;//0摩通 1 国贸
        }
        #endregion
    }
}
